package com.wang.chatbot.api.domain.ai.service.Imp;

import com.alibaba.fastjson.JSON;
import com.wang.chatbot.api.domain.ai.model.aggregate.AiAggregate;
import com.wang.chatbot.api.domain.ai.service.IAiApi;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLEngineResult;
import java.io.IOException;

/**
 * @author Your Name
 * @date 2025/11/8 16:17
 * <Description of the class>
 */
@Service
public class AiApi implements IAiApi {
    @Value("${Ai.apiKey}")
    private String apiKey;
    @Value("${Ai.apiUrl}")
    private String apiUrl;
    @Override
    public String doChat(String question) throws IOException {
        Logger logger = LoggerFactory.getLogger(IAiApi.class);

        // ✅ 必须指定 model（替换成你实际的模型ID）
        String modelId = "xop3qwen1b7"; // 示例，请根据控制台填写
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(apiUrl);
        post.setHeader("Authorization", "Bearer " + apiKey);
        post.setHeader("Content-Type", "application/json");

        String jsonPayload = """
        {
          "model": "%s",
          "messages": [{"role": "user", "content": "%s"}]
        }
        """.formatted(modelId,question);
        StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
        post.setEntity(requestEntity);
        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            logger.info("提问成功");
            HttpEntity entity = response.getEntity();
            String respStr=EntityUtils.toString(entity);
            AiAggregate answerClass = JSON.parseObject(respStr, AiAggregate.class);
            return answerClass.getChoices().get(0).getMessage().getContent();
        }else {
            logger.info("提问失败");
            throw new RuntimeException("请求失败"+response.getStatusLine().getStatusCode());
        }
    }
}
